<template>
	<el-container>
		<el-main class="nopadding">
			<!-- 使用 el-row 和 el-col 调整按钮位置 -->
			<el-row style="margin-bottom: 10px; margin-top: 10px;">
				<el-col :span="24" style="text-align: left;">
<!--					<el-button type="primary" round @click="openAddForm" style="padding: 10px 20px;">新增数据</el-button>-->
				</el-col>
			</el-row>
			<el-table ref="table" :data="paginatedData">
				<el-table-column label="#" type="index" width="50"></el-table-column>
				<el-table-column label="申请人" prop="userName" ></el-table-column>
<!--				<el-table-column label="申请人部门" prop="deptName" ></el-table-column>-->
				<el-table-column label="审批人" prop="approverName" ></el-table-column>
				<el-table-column label="审批人部门" prop="approverDeptName" ></el-table-column>
				<el-table-column label="采购事由" prop="subjectMatter"  :show-overflow-tooltip="true"></el-table-column>
				<el-table-column label="采购类别" prop="category" ></el-table-column>
				<el-table-column label="期望交付时间" prop="deliveryTime" :show-overflow-tooltip="true"></el-table-column>
<!--				<el-table-column label="状态" prop="status" ></el-table-column>-->
				<el-table-column label="状态" prop="status">
					<template #default="scope">
						<span v-if="scope.row.status === '0'">审核中</span>
						<span v-else-if="scope.row.status === '1'">通过</span>
						<span v-else-if="scope.row.status === '2'">驳回</span>
						<span v-else-if="scope.row.status === '3'">初始化</span>
						<span v-else-if="scope.row.status === '99'">撤销</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" fixed="right" align="right">
					<template #default="scope">
						<el-button-group>
							<!-- 新增按钮 -->
<!--							<el-button text type="primary" size="small" @click="showFlow(scope.row)">查看当前流程信息</el-button>-->
							<el-button text type="primary" size="small" @click="showCostDetails(scope.row)">费用明细详情</el-button>

						</el-button-group>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				:current-page="search.page"
				:page-size="search.pageSize"
				layout="total, prev, pager, next"
				:total="total">
			</el-pagination>
		</el-main>
		<!-- 新增弹窗 -->
		<el-dialog v-model="dialogVisible" title="费用明细" width="60%">
			<el-table :data="purchaseDetailsList">
				<el-table-column label="费用明细名称" prop="detailName" ></el-table-column>
				<el-table-column label="规格" prop="specs" ></el-table-column>
				<el-table-column label="数量" prop="number" ></el-table-column>
				<el-table-column label="金额" prop="amount" ></el-table-column>
			</el-table>
			<template #footer>
				<el-button @click="dialogVisible = false">关闭</el-button>
			</template>
		</el-dialog>
<!--		&lt;!&ndash; 流程弹窗展示 &ndash;&gt;-->
<!--		<el-dialog v-model="oaFlowsVisible" title="审批流程" width="60%">-->
<!--			<el-table :data="oaFlows">-->
<!--			<div class="approval-content">-->
<!--				<div class="approval-section">-->
<!--					<div class="info-item">-->
<!--						<span>审批人：</span>-->
<!--						<span>oaFlows[0].applicantName</span>-->
<!--					</div>-->
<!--					<div class="info-item">-->
<!--						<span>审批日期：</span>-->
<!--						<span>2023-04-01</span>-->
<!--					</div>-->
<!--					<div class="info-item">-->
<!--						<span>审批时间：</span>-->
<!--						<span>10:30</span>-->
<!--					</div>-->
<!--					<div class="info-item">-->
<!--						<span>审批类型：</span>-->
<!--						<span>采购申请</span>-->
<!--					</div>-->
<!--					<div class="info-item">-->
<!--						<span>审批结果：</span>-->
<!--						<span>同意（最终未通过财务审批）</span>-->
<!--					</div>-->
<!--				</div>-->
<!--				<div class="approval-section">-->
<!--					<h3>审批流程</h3>-->
<!--					<div class="process-item">-->
<!--						<span>发起人：</span>-->
<!--						<span>阿萨德</span>-->
<!--						<span class="date">2025-03-31 10:30</span>-->
<!--					</div>-->
<!--					<div class="process-item success">-->
<!--						<span>部门审批：</span>-->
<!--						<span>已通过</span>-->
<!--						<div class="details">-->
<!--							<span>审批人：李四</span>-->
<!--							<span class="date">2023-04-01 10:30</span>-->
<!--							<span>备注：部门预算充足，同意此申请</span>-->
<!--						</div>-->
<!--					</div>-->
<!--					<div class="process-item warning">-->
<!--						<span>财务审批：</span>-->
<!--						<span>已驳回</span>-->
<!--						<div class="details">-->
<!--							<span>审批人：王五</span>-->
<!--							<span class="date">2023-04-02 14:20</span>-->
<!--							<span>备注：超出本季度采购预算限额，建议下季度再申请</span>-->
<!--						</div>-->
<!--					</div>-->
<!--					<div class="process-item">-->
<!--						<span>总经理审批：</span>-->
<!--						<span>（未进行）</span>-->
<!--					</div>-->
<!--				</div>-->
<!--			</div>-->
<!--			</el-table>-->
<!--		</el-dialog>-->


		<!-- 新增表单弹窗 -->
		<el-dialog v-model="addFormVisible" title="新增数据" width="60%">

			<el-form :model="formData" label-width="120px">
				<el-form-item label="申请人">
<!--					<el-input v-model="formData.userName" readonly></el-input>-->
<!--					<el-button type="primary" @click="openSelectUserDialog">选择人员</el-button>-->
					<!-- 引入 selectUserDialog 组件 -->
					<select-user-dialog ref="selectUserDialog" @success="onUserSelected" ></select-user-dialog>
				</el-form-item>
<!--				<el-form-item label="申请人部门">-->
<!--					<el-input v-model="formData.userDeptName"></el-input>-->
<!--				</el-form-item>-->
				<el-form-item label="审批人">
    <multi-select-personnel-module ref="multiSelectPersonnelModule" :mode="true" @success="onApproverSelected" ></multi-select-personnel-module>
                 </el-form-item>
<!--				<el-form-item label="审批人部门">-->
<!--					<el-input v-model="formData.approverDeptName"></el-input>-->
<!--				</el-form-item>-->
				<el-form-item label="采购事由">
					<el-input v-model="formData.purchase.subjectMatter"></el-input>
				</el-form-item>
				<el-form-item label="采购类别">
					<el-input v-model="formData.purchase.category"></el-input>
				</el-form-item>
				<el-form-item label="期望交付时间">
					<el-date-picker v-model="formData.purchase.deliveryTime" type="date" placeholder="选择日期"></el-date-picker>
				</el-form-item>
				<el-form-item label="费用明细">
					<el-table :data="formData.purchaseDetailsList">
						<el-table-column label="费用明细名称" prop="detailName">
							<template #default="{ row, $index }">
								<el-input v-model="formData.purchaseDetailsList[$index].detailName"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="规格" prop="specification">
							<template #default="{ row, $index }">
								<el-input v-model="formData.purchaseDetailsList[$index].specs"></el-input>
							</template>
						</el-table-column>
						<el-table-column label="数量" prop="quantity">
							<template #default="{ row, $index }">
								<el-input-number v-model="formData.purchaseDetailsList[$index].number"></el-input-number>
							</template>
						</el-table-column>
						<el-table-column label="金额" prop="amount">
							<template #default="{ row, $index }">
								<el-input-number v-model="formData.purchaseDetailsList[$index].amount"></el-input-number>
							</template>
						</el-table-column>
						<el-table-column label="操作" fixed="right" align="right">
							<template #default="{ $index }">
								<el-button type="danger" size="small" @click="removeCostDetail($index)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
					<el-button type="primary" @click="addCostDetail">添加费用明细</el-button>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button @click="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click="submitForm">提交</el-button>
			</template>
		</el-dialog>

	</el-container>
</template>

<script>
import multiSelectPersonnelModule from '@/views/module/selectUserDialogGetUserDeptId.vue';
import selectUserDialog from '@/views/module/selectUserDialogGetUserDeptId.vue';

export default {
    components: {
		multiSelectPersonnelModule,
		selectUserDialog
    },
	data() {
		return {
			oaFlows:[],
			oaFlowsVisible:false,
			apiObj: undefined,
			paginatedData:null,
			search: {
				date: '',
				id: '',
				page: 1,
				pageSize: 15 // 修改：将默认分页大小从10改为15
			},
			total: 0, // 总记录数
			dialogVisible: false, // 控制弹窗显示
			// purchaseDetailsList: [], // 存储费用明细数据
			addFormVisible: false, // 控制新增表单弹窗显示
			formData: {
				purchase:{},
				purchaseDetailsList:[],
				oaFlows:[],
			}
			// formData: {
			// 	userName: '',
			// 	userDeptName: '',
			// 	approverUserName: '',
			// 	approverDeptName: '',
			// 	purchaseReason: '',
			// 	purchaseCategory: '',
			// 	expectedDeliveryTime: '',
			// 	purchaseDetailsList: [
			// 		{ detailName: '', specification: '', quantity: 0, amount: 0 }
			// 	]
			// }
		};
	},
	mounted() {
		console.log("apiObj", this.apiObj)
		let userInfo = this.$TOOL.data.get("USER_INFO");
		// console.log("111111111111111111111111", userInfo);
		if (userInfo && userInfo.id) {
			this.search.id = userInfo.id;
			this.fetchData();
		} else {
			console.error("USER_INFO is undefined or invalid");
		}
	},
	computed: {
		// paginatedData() {
		// 	const start = (this.search.page - 1) * this.search.pageSize;
		// 	const end = start + this.search.pageSize;
		// 	let paginated = this.apiObj ? this.apiObj.slice(start, end) : [];
		// 	// 新增50条假数据
		// 	paginated = paginated.concat(Array.from({ length: 50 }, (_, i) => ({
		// 		id: `fake${i + 1}`,
		// 		userName: `假用户${i + 1}`,
		// 		userDeptName: `假部门${i + 1}`,
		// 		approverUserName: `假审批人${i + 1}`,
		// 		approverDeptName: `假审批部门${i + 1}`,
		// 		purchaseReason: `测试采购${i + 1}`,
		// 		purchaseCategory: `类别${String.fromCharCode(65 + (i % 26))}`,
		// 		expectedDeliveryTime: `2023-10-${String(i + 1).padStart(2, '0')}`
		// 	})));
		// 	return paginated;
		// }
	},
	methods: {
		filterChange(data) {
			this.search.date = data.date;
			this.fetchData();
		},
		fetchData() {
			let userInfo = this.$TOOL.data.get("USER_INFO");
			this.$API.office.personalFinance.getPurchaseByPurchaser.get({
				option1:userInfo.id,
				page: this.search.page,
				pageSize: this.search.pageSize
			}).then(res => {
				console.log('res:', res);
					this.paginatedData = res.data.list;
					this.total = res.data.total; // 假设接口返回的总记录数字段为 total
				console.log('this.paginatedData:', this.paginatedData);
			}).catch(err => {
				console.error("接口调用失败", err);
			});
		},
		handleSizeChange(newSize) {
			this.search.pageSize = newSize;
			this.fetchData();
		},
		handleCurrentChange(newPage) {
			this.search.page = newPage;
			this.fetchData();
		},
		readBpmDetails(row, index) {
			this.$nextTick(() => {
				this.$router.replace({
					path: '/bpm/handle/read',
					query: {
						runId: row.runId
					}
				});
			});
		},
		openAddForm() {
			this.addFormVisible = true;
		},
		addCostDetail() {
			this.formData.purchaseDetailsList.push({ detailName: '', specification: '', quantity: 0, amount: 0 });
		},
		removeCostDetail(index) {
			this.formData.purchaseDetailsList.splice(index, 1);
		},
		submitForm() {
			let userInfo = this.$TOOL.data.get("USER_INFO");
			this.formData.purchase.purchaser = userInfo.id;
			this.formData.purchase.status = '0'; //	状态 0审核中 1通过 2不通过

			this.formData.oaFlows.applicant = this.formData.userId;
			this.formData.oaFlows.applicantDeptId = this.formData.userDeptId;

			console.log(this.formData)
		},
		showCostDetails(row) {
			// 模拟获取费用明细数据，新增50条假数据
			// this.purchaseDetailsList = Array.from({ length: 50 }, (_, i) => ({
			// 	detailName: `明细${i + 1}`,
			// 	specification: `规格${String.fromCharCode(65 + (i % 26))}`,
			// 	quantity: (i + 1) * 10,
			// 	amount: (i + 1) * 100
			// }));
			this.purchaseDetailsList = row.purchaseDetails;
			this.dialogVisible = true; // 显示弹窗
		},

		openSelectUserDialog() {
			this.$refs.selectUserDialog.visible = true;
		},
		onUserSelected(selectedUsers) {
			console.log('Selected Users:', selectedUsers);
			if (selectedUsers && selectedUsers.length > 0) {
				this.formData.userId = selectedUsers[0].userId;
				this.formData.userName = selectedUsers[0].userName;
				this.formData.userDeptId = selectedUsers[0].userDeptId;
				this.formData.userDeptName = selectedUsers[0].userDeptName;
			}
			console.log('this.formData',this.formData)
		},
		onApproverSelected(selectedUsers) {
			console.log('Selected Approvers:', selectedUsers);
			if (selectedUsers && selectedUsers.length > 0) {
				this.formData.oaFlows = selectedUsers.map(user => ({
					userId: user.userId,
					userName: user.userName,
					userDeptId: user.userDeptId,
					userDeptName: user.userDeptName
				}));
			}
			console.log('this.ApproversFormData', this.formData);
		},
		showFlow(row) {
			this.oaFlows = row.oaFlows;
			this.oaFlowsVisible = true; // 显示弹窗
		}

	}
}
</script>

<style>
</style>
